//
//  XKLoginViewController.m
//  xk100
//
//  Created by xiaokang on 2017/6/6.
//  Copyright © 2017年 xiaokang. All rights reserved.
//

#import "XKLoginViewController.h"
#import "XKMainTabBarController.h"
#import "XKForgetPwdViewController.h"
#import "XKRegisterViewController.h"

#import "HcdGuideView.h"

#import "XKLoginView.h"
#import <Photos/Photos.h>

@interface XKLoginViewController () <XKLoginViewDelegate>
@property (nonatomic, strong) XKLoginView *loginView;
@end

@implementation XKLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubviews];
    [self setGuidePage];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    
    [[LocationManager shareInstance] getCurrentLocationByViewController:self resultBlock:^(CLLocation *location, CLPlacemark *placeMark, NSString *error) {
        if (error) {
            NSLog(@"定位出错,错误信息:%@",error);
        }else{
            NSLog(@"定位成功:经度:%f 纬度:%lf 当前地址:%@-%@-%@  \n location详细信息:%@ \n ",location.coordinate.latitude, location.coordinate.longitude,placeMark.country, placeMark.locality,placeMark.subLocality,placeMark.name);
            
            [UserDefaults setObject:placeMark.country withKey:@"current_country"]; // 国家
            [UserDefaults setObject:placeMark.locality withKey:@"current_locality"]; // 城市
            [UserDefaults setObject:placeMark.subLocality withKey:@"current_subLocality"]; // 街区
            [UserDefaults setObject:placeMark.subLocality withKey:@"current_name"]; // 详细地址
        }

    }];
    
    
    
    
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [self.view endEditing:YES];
}


#pragma mark - 初始化视图
- (void)initSubviews {
    _loginView = [[XKLoginView alloc] init];
    _loginView.frame = self.view.bounds;
    _loginView.delegate = self;
    [self.view addSubview:_loginView];
    
    // 该BOOL值用于同一个账户在不同客户端登录后 来判断是否进行网络请求操作 登录页面出现时默认设置可操作
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isCanOperation"];
    
}


#pragma mark - XKLoginViewDelegate
- (void)loginWithPhone:(NSString *)phoneString password:(NSString *)password {
    if (![phoneString isMobileNumber]) {
        [SVProgressHUD showErrorWithStatus:@"手机号格式错误!"];
        return;
    }
    
    [SVProgressHUD show];
    
    // 获取推送时的 deviceToken 值传给后台服务器
    NSString *deviceToken = [UserDefaults objectWithKey:@"push_deviceToken"];
    
    [APIManager POSTRequestWith:APIPOSTRequestState_Login parameters:@{@"phone":phoneString, @"pwd": password, @"deviceToken":deviceToken} successBlock:^(NSDictionary *successDict) {
        NSLog(@"%@",[NSString jsonToString:successDict]);
        BOOL isSuccess = [UserDefaults setObjectWithData:successDict[@"data"]];
        if (isSuccess) {
            [MobClick event:@"LoginSuccess"]; // 友盟事件统计
            // 保存账号密码
            [UserDefaults setObject:phoneString withKey:@"USER_ACCOUNT"];
            
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLoginSuccess"];
            
            if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isRemberPassword"]) {
                [SAMKeychain setPassword:password forService:[[NSBundle mainBundle] bundleIdentifier] account:phoneString];
            }
            
            [UserDefaults setObject:successDict[@"msg"] withKey:@"msg"];
            [MobClick profileSignInWithPUID:successDict[@"data"][@"uid"]];// 友盟用户账户统计
            
            // 切换 window 根控制器
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            window.rootViewController = [[XKMainTabBarController alloc] init];
            
        } else {
            [SVProgressHUD showErrorWithStatus:@"用户数据获取失败!"];
        }
    } failureBlock:^(NSDictionary *failureDict) {
        
    } errorBlock:^(NSError *error) {
        
    }];
}

- (void)forgetPasswordWithPhone:(NSString *)phoneString {
    XKForgetPwdViewController * forgetVC = [[XKForgetPwdViewController alloc] init];
    forgetVC.phoneString = [phoneString isMobileNumber] ? phoneString :@"";
    [self.navigationController pushViewController:forgetVC animated:YES];
}

-(void)fastRegisterWithPhone:(NSString *)phoneString {
    XKRegisterViewController * registerVC = [[XKRegisterViewController alloc] init];
    registerVC.phoneString = [phoneString isMobileNumber] ? phoneString :@"";
    [self.navigationController pushViewController:registerVC animated:YES];
}


#pragma mark - 新特性
- (void)setGuidePage {
    NSMutableArray *images = [NSMutableArray new];
    
    //    [images addObject:[UIImage imageNamed:@"start_bg1"]];
    [images addObject:[UIImage imageNamed:@"start_bg2"]];
    [images addObject:[UIImage imageNamed:@"start_bg3"]];
    [images addObject:[UIImage imageNamed:@"start_bg4"]];
    
    [[HcdGuideViewManager sharedInstance] showGuideViewWithImages:images
                                                   andButtonTitle:@"立即体验"
                                              andButtonTitleColor:[UIColor redColor]
                                                 andButtonBGColor:[UIColor clearColor]
                                             andButtonBorderColor:[UIColor redColor]];
}











- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
